package com.exteam.common.network;

/**
 * 异步加载文件
 *
 * @author sean.yang
 */

import android.content.Context;
import android.os.AsyncTask;
import android.widget.ProgressBar;

import com.exteam.common.util.CommLogger;
import com.exteam.common.util.CommUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class SyncDownLoader {

    private OnDownLoadListener fileLoadListener;

    private InflateDownLoadTask downTask;

    private ProgressBar progressBar;


    private Context ctx;


    public SyncDownLoader(Context ctx, DownloadFile downFile, OnDownLoadListener fileLoadListener) {
        this.ctx = ctx;
        this.fileLoadListener = fileLoadListener;
        downTask = new InflateDownLoadTask();
        downTask.execute(downFile);

    }


    public OnDownLoadListener getFileLoadListener() {
        return fileLoadListener;
    }

    public ProgressBar getProgressBar() {
        return progressBar;
    }


    public void setProgressBar(ProgressBar progressBar) {
        this.progressBar = progressBar;
    }

    public interface OnDownLoadListener {
        public void onFileLoad(DownloadFile downFile, ProgressBar progressBar);

        public void onFileError(DownloadFile downFile, ProgressBar progressBar, String errMessage);

        public void onProgress(DownloadFile downFile, ProgressBar progressBar, int progress);

    }

    class InflateDownLoadTask extends AsyncTask<Object, Object, Object> {

        String fileId;
        String url;
        DownloadFile currFile;
        boolean isDownSuccess = false;

        public InflateDownLoadTask() {

        }

        @Override
        protected void onPostExecute(Object result) {
            // 通知UI更新
            // DataLog.debug("onPostExecute index:"+indexId);

            if ((Boolean) result && fileLoadListener != null) {
                fileLoadListener.onFileLoad(currFile, progressBar);
            }
        }

        @Override
        protected Object doInBackground(Object... args) {

            // 获得下载文件对象
            currFile = (DownloadFile) args[0];
            // 得到下载的文件URL
            String url = currFile.getFilePath();
            // 获取一个唯一的名字
            String name = CommUtils.md5(url)
                    + url.substring(url.lastIndexOf("."));

//			String filePath = "";
//			File fileDir = null;
            // 判断sd卡是否存在
//			boolean sdCardExist = Environment.getExternalStorageState().equals(
//					Environment.MEDIA_MOUNTED);
//			// 如果存在，构建一个mobilestudy目录
//			if (sdCardExist) {
//				fileDir = new File(Environment.getExternalStorageDirectory(),
//						"shangde");
//				// 如果目录不存在，就构建新的目录
//				if (!fileDir.exists()) {
//					fileDir.mkdir();
//				}
//				CommLogger.d("fileDir isDirectory" + fileDir.isDirectory() + " fileDir.exists()" + fileDir.exists());
//				filePath = fileDir.getAbsolutePath(); // sd卡
//				CommLogger.d("filePath:" + filePath);
//			} else {
//				// 如果没有sd卡，放在沙箱目录
//				fileDir = ctx.getFilesDir(); // 私有目录
//				filePath = fileDir.getPath();
//				CommLogger.d("filePath" + filePath);
//			}

            // 构建下载文件
            //currFile.getFilePath()
            File file = new File(currFile.getLocalFilePath());
            CommLogger.d("start down..." + currFile.toString());
            InputStream inputStream = null;

            FileOutputStream fos = null;
            long currSize = 0;
            try {
                // 如果文件不存在，构建一个新文件
                if (!file.exists()) {
                    file.createNewFile();
                }


                // 获取文件大小
                //HttpResponse response = CommUtils.getResponseFromServerByGet(url);
                long size = CommUtils.getUrlFileSize(url);
                currFile.setFileSize(size);
                CommLogger.d(" down... url:" + url + "  size:" + currFile.getFileSize());
                //currFile.setLocalFilePath(file.getAbsolutePath());
                CommLogger.d(" down... setFileSize " + currFile.toString() + " file.length()" + file.length());

                // 如果存在本地，则不去服务器下载
                if (file.length() == currFile.getFileSize()) {
                    CommLogger.d(" downloaded not down");
                    //progressBar.setProgress(100);
                    //if(fileLoadListener!=null){

                    //	fileLoadListener.onFileLoad(currFile,progressBar);
                    //}
                    return isDownSuccess;
                }

                // 获取下载的流
                inputStream = CommUtils.getDataFromServerByGet(url);
                if (inputStream == null) {
                    return null;
                }
                // 每次多取5K数据
                byte[] data = new byte[1024 * 5];

                fos = new FileOutputStream(file);

                // 继续上次下载
                int readSize = 0;
                while ((readSize = inputStream.read(data)) != -1) {
                    // 边读边写
                    fos.write(data, 0, readSize);

                    currSize += readSize;
                    onProgressUpdate(currSize);

                }
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                CommLogger.d(" down... :" + e.toString());
                if (fileLoadListener != null) {

                    fileLoadListener.onFileError(currFile, progressBar, e.toString());
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                CommLogger.d(" down... :" + e.toString());
                if (fileLoadListener != null) {

                    fileLoadListener.onFileError(currFile, progressBar, e.toString());
                }
            } finally {
                try {
                    if (fos != null) {
                        fos.close();
                    }
                    if (inputStream != null) {
                        inputStream.close();
                    }

                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    if (fileLoadListener != null) {

                        fileLoadListener.onFileError(currFile, progressBar, e.toString());
                    }
                }
            }

            return isDownSuccess;
        }

        @Override
        protected void onProgressUpdate(Object... values) {
            // TODO Auto-generated method stub
            long currValue = (Long) values[0];
            int per = (int) ((currValue * 1.0f / currFile.getFileSize()) * 100);
            CommLogger.d("fileSize:" + currFile.getFileSize() + " curr:" + currValue + " per" + per);

            // 返回本地存储路径
            if (currValue == currFile.getFileSize()) {
                currFile.setTag(1);  // 完成

                CommLogger.d("downOK" + currFile.toString());
                per = 100;
                this.isDownSuccess = true;
                if (fileLoadListener != null) {

                    //fileLoadListener.onFileLoad(currFile,progressBar);
                    fileLoadListener.onProgress(currFile, progressBar, per);
                }
            }
            if (fileLoadListener != null) {

                fileLoadListener.onProgress(currFile, progressBar, per);
            }
            super.onProgressUpdate(values);
        }

    }
}
